import JsonP from 'jsonp'
import axios from 'axios'
import {Modal} from 'antd'
import Utils from './../utils/utils'

export default class Axios {
    static jsonp(options) {
        return new Promise((resolve, reject) => {
            JsonP(options.url, {
                param: 'callback'
            }, function (err, response) {
                if (response.status === 'success') {
                    resolve(response);
                } else {
                    reject(response.messsage);
                }
            })
        })
    }
    static ajax(options) {
        let loading;
        if (options.data && options.data.isShowLoading !== false){
            loading = document.getElementById('ajaxLoading');
            loading.style.display = 'block';
        }
        let baseApi=''
        //判断时mock地址还时接口地址
        if(options.isMock) {
            baseApi="https://www.easy-mock.com/mock/5bc55b96869c55589bda3296/mockapi"
        }else {
            baseApi="https://www.easy-mock.com/mock/5bc55b96869c55589bda3296/mockapi"
        }
        return new Promise((resolve,reject) => {
            axios({
                url:options.url,
                method:'get',
                baseURL:baseApi,
                timeout:5000,
                //判断option是否有data或者data里面是否有参数
                params:(options.data && options.data.params) || ''
            }).then((response)=>{
                if (options.data && options.data.isShowLoading !== false) {
                    loading = document.getElementById('ajaxLoading');
                    loading.style.display = 'none';
                }
                if(response.status === 200){
                    let res = response.data
                    if(res.code === 0) {
                        resolve(res)
                    }else {
                        Modal.info({
                            title:'提示',
                            content:res.message
                        })
                    }
                }else {
                    reject(response.data)
                }
            })
        })
    }
    static requestList = (_this,url,params,isMock) => {
        var data = {
            params:params,
            isMock
        }
        console.log(this)
        Axios.ajax({
            url,
            data
        }).then(res => {
            console.log(res)
            if(res && res.result) {
                res.result.item_list.map((item,index) => {
                    return item.key = index
                })
                _this.setState({
                    dataSource:res.result.item_list,
                    pagination:Utils.pagination(res,(current) => {
                        _this.params.page = current
                        _this.requestList()
                    })
                })
            }
        })
    }
}